﻿(function ($) {
    $.fn.flexGetSelection = function () {
        if (!$(this).is('table') || $(this).closest('div.flexigrid').length === 0)
            throw "flexGetSelection only operates on flexigrid tables.";

        var rows = $(this).find('tr.trSelected');
        var result = new Object();
        result.total = rows.length;

        if (rows.length > 0) {
            result.rows = new Array();
            $(rows).each(function (rowIndex, tr) {
                var rowId = $(tr).attr('id');
                result.rows[rowIndex] = new Object();
                result.rows[rowIndex].id = rowId.substring(3);

                result.rows[rowIndex].cell = new Object();
                $(tr).find('td').each(function (colIndex, td) {
                    var colName = $(td).attr('abbr');
                    var colValue = $(td).find('div').text();
                    result.rows[rowIndex].cell[colName] = colValue;
                });
            });
        }

        return result;
    };

    //  options: {
    //      colIndex:   <0-based integer>
    //      template:   <markup that replaces cell content>
    //      templateId: <The ID of a script block that contains the templated markup>
    //  }
    //
    //  template variables:
    //      {{col}}     The ordinal of the column.
    //      {{id}}      The id of the row
    //      {{row}}     The ordinal of the row.
    //      {{text}}    The original text of the column
    $.fn.flexTemplate = function (options) {
        if (!$(this).is('table') || $(this).closest('div.flexigrid').length === 0)
            throw "flexTemplate only operates on flexigrid tables.";

        if (options === undefined)
            throw "flexTemplate options missing";

        if (options.colIndex === undefined || (options.template === undefined && options.templateId === undefined))
            throw "flexTemplate options malformed";

        var colIndex = options.colIndex;
        var template = options.template ? options.template : $('#' + options.templateId).html();

        $(this).find('tr').each(function (index, tr) {
            var rowId = $(tr).attr('id');
            var itemId = rowId.substring(3);
            if (itemId === undefined)
                itemId = "";

            var div = $(tr).find('td').eq(colIndex).find('div');
            var text = $(div).text();

            var markup = template;
            markup = markup.replace("{{col}}", colIndex);
            markup = markup.replace("{{id}}", itemId);
            markup = markup.replace("{{row}}", index);
            markup = markup.replace("{{text}}", text);
            $(div).html(markup);
        });

        return this;
    }
})(jQuery);